﻿using BLL.Sgf;
using BLL.Utility;
using Entity.Models;
using Sgf.Utility;
using System;
using System.Web.Security;
using System.Web.UI.WebControls;

namespace Sgf
{
    public partial class Login : AbstractPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Login1.Focus();
        }

        #region -- Métodos Protected --
        protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
        {
            using (var bll = new UsuarioBLL())
            {
                var pEntity = GetEntity();
                GerarBanco();
                var acesso = bll.ValidaAcesso(pEntity);
                if (acesso)
                {
                    e.Authenticated = true;
                    FormsAuthentication.RedirectFromLoginPage(Login1.UserName, false);
                    var usuarioId = bll.BuscaUsuario(pEntity);
                    Session["UsuarioId"] = usuarioId.Id;
                    Response.Redirect("~/Inicio.aspx");
                }
                else if (pEntity.NomeUsuario.Equals("admin") && pEntity.SenhaUsuario.Equals("7C87541FD3F3EF5016E12D411900C87A6046A8E8"))
                {
                    e.Authenticated = true;
                    FormsAuthentication.RedirectFromLoginPage(Login1.UserName, false);
                    try
                    {
                        const int id = 0;
                        Session["UsuarioId"] = id;
                        Response.Redirect("~/Inicio.aspx");
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Login.GeraDb :: " + ex.Message, ex);
                    }
                }
                else
                {
                    e.Authenticated = false;
                }
            }
        }
        #endregion

        #region -- Métodos Privados --
        private Usuario GetEntity()
        {
            var pEntity = new Usuario();
            var criptografar = new Criptografar();
            pEntity.NomeUsuario = Login1.UserName;
            pEntity.SenhaUsuario = criptografar.HashValue(Login1.Password);
            return pEntity;
        }

        private void LimparCampos()
        {
            var campos = new Campos();
            campos.LimparTextBox(this);
        }

        private static void GerarBanco()
        {
            try
            {
                using (var gdb = new GeraDb())
                {
                    gdb.GeraDbDadosContext();
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Login.GerarBanco :: " + ex.Message, ex);
            }
        }
        #endregion

    }
}